From 9fb0f80e84f752e3b3c4ae5e1071a6edcbf56b94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Diego=20Elio=20Petten=C3=B2?= Date: Sat, 14 Mar 2020 18:13:55 +0000 Subject: Now that Python 3.6 is the minimum supported version, use f-strings. The f-strings formatted strings are generally simpler to write, read and debug, with a few exceptions. Keep the logging strings lazy, keep the CSV-building with %-formatting, as it makes it more readable. In fsoptium, keep `'$%s\r\n'` as a %-format, to avoid making it `f'${command}\r\n'` that would make it easy to mistake for a Shell variable. --- glucometerutils/common.py | 17 +++++------------ glucometerutils/drivers/accuchek_reports.py | 4 ++-- glucometerutils/drivers/fslibre.py | 24 ++++++++++-------------- glucometerutils/drivers/fsoptium.py | 2 +- glucometerutils/drivers/otultraeasy.py | 3 +-- glucometerutils/drivers/otverio2015.py | 7 ++++--- glucometerutils/drivers/sdcodefree.py | 4 ++-- glucometerutils/drivers/td4277.py | 4 ++-- glucometerutils/exceptions.py | 9 +++------ glucometerutils/glucometer.py | 12 ++++-------- glucometerutils/support/contourusb.py | 10 +++++----- glucometerutils/support/freestyle.py | 12 ++++-------- glucometerutils/support/hiddevice.py | 6 ++---- glucometerutils/support/lifescan.py | 6 +++--- reversing_tools/abbott/freestyle_hid_console.py | 4 ++-- 15 files changed, 50 insertions(+), 74 deletions(-) diff --git a/glucometerutils/common.py b/glucometerutils/common.py index 6576ebd..50f04e7 100644 --- a/glucometerutils/common.py +++ b/glucometerutils/common.py @@ -154,23 +154,16 @@ class MeterInfo: version_information_string = "\n ".join(self.version_info).strip() base_output = textwrap.dedent( - """\ - {model} - Serial Number: {serial_number} + f"""\ + {self.model} + Serial Number: {self.serial_number} Version Information: {version_information_string} - Native Unit: {native_unit} + Native Unit: {self.native_unit.value} """ - ).format( - model=self.model, - serial_number=self.serial_number, - version_information_string=version_information_string, - native_unit=self.native_unit.value, ) if self.patient_name != None: - base_output += "Patient Name: {patient_name}\n".format( - patient_name=self.patient_name - ) + base_output += f"Patient Name: {self.patient_name}\n" return base_output diff --git a/glucometerutils/drivers/accuchek_reports.py b/glucometerutils/drivers/accuchek_reports.py index c4d7527..e6dc2ea 100644 --- a/glucometerutils/drivers/accuchek_reports.py +++ b/glucometerutils/drivers/accuchek_reports.py @@ -57,7 +57,7 @@ class Device(driver_base.GlucometerDriver): report_files = glob.glob(reports_path) if not report_files: raise exceptions.ConnectionFailed( - 'No report file found in path "%s".' % reports_path + f'No report file found in path "{reports_path}".' ) self.report_file = report_files[0] @@ -80,7 +80,7 @@ class Device(driver_base.GlucometerDriver): def get_meter_info(self): return common.MeterInfo( - "%s glucometer" % self.get_model(), + f"{self.get_model()} glucometer", serial_number=self.get_serial_number(), native_unit=self.get_glucose_unit(), ) diff --git a/glucometerutils/drivers/fslibre.py b/glucometerutils/drivers/fslibre.py index 29e821a..4802673 100644 --- a/glucometerutils/drivers/fslibre.py +++ b/glucometerutils/drivers/fslibre.py @@ -162,28 +162,24 @@ def _parse_arresult(record): comment_parts.append("Medication") if parsed_record["food-flag"]: - if parsed_record["food-carbs-grams"]: - comment_parts.append("Food (%d g)" % parsed_record["food-carbs-grams"]) + grams = parsed_record["food-carbs-grams"] + if grams: + comment_parts.append(f"Food ({grams} g)") else: comment_parts.append("Food") if parsed_record["long-acting-flag"]: - if parsed_record["double-long-acting-insulin"]: - comment_parts.append( - "Long-acting insulin (%.1f)" - % (parsed_record["double-long-acting-insulin"] / 2.0) - ) + insulin = parsed_record["double-long-acting-insulin"] / 2 + if insulin: + comment_parts.append(f"Long-acting insulin ({insulin:.1f})") else: comment_parts.append("Long-acting insulin") if parsed_record["rapid-acting-flag"]: - # provide default value, as this record does not always exist - # (even if rapid-acting-flag is set) - if parsed_record.get("double-rapid-acting-insulin", 0): - comment_parts.append( - "Rapid-acting insulin (%.1f)" - % (parsed_record["double-rapid-acting-insulin"] / 2.0) - ) + # This record does not always exist, so calculate it only when present. + if "double-rapid-acting-insulin" in parsed_record: + rapid_insulin = parsed_record["double-rapid-acting-insulin"] / 2 + comment_parts.append(f"Rapid-acting insulin ({rapid_insulin:.1f})") else: comment_parts.append("Rapid-acting insulin") diff --git a/glucometerutils/drivers/fsoptium.py b/glucometerutils/drivers/fsoptium.py index 5c3971e..77244af 100644 --- a/glucometerutils/drivers/fsoptium.py +++ b/glucometerutils/drivers/fsoptium.py @@ -89,7 +89,7 @@ class Device(serial.SerialDevice, driver_base.GlucometerDriver): DEFAULT_CABLE_ID = "1a61:3420" def _send_command(self, command): - cmd_bytes = bytes("$%s\r\n" % command, "ascii") + cmd_bytes = bytes(f"$%s\r\n" % command, "ascii") logging.debug("Sending command: %r", cmd_bytes) self.serial_.write(cmd_bytes) diff --git a/glucometerutils/drivers/otultraeasy.py b/glucometerutils/drivers/otultraeasy.py index 0d1e7a9..ba8067f 100644 --- a/glucometerutils/drivers/otultraeasy.py +++ b/glucometerutils/drivers/otultraeasy.py @@ -152,8 +152,7 @@ class Device(serial.SerialDevice, driver_base.GlucometerDriver): pkt.link_control.sequence_number != self.expect_receive_ ): raise lifescan.MalformedCommand( - "at position 2[0b] expected %02x, received %02x" - % (self.expect_receive_, pkt.link_connect.sequence_count) + f"at position 2[0b] expected {self.expect_receive_:02x}, received {pkt.link_connect.sequence_count:02x}" ) return pkt diff --git a/glucometerutils/drivers/otverio2015.py b/glucometerutils/drivers/otverio2015.py index b8429ea..fee84f0 100644 --- a/glucometerutils/drivers/otverio2015.py +++ b/glucometerutils/drivers/otverio2015.py @@ -123,7 +123,7 @@ class Device(driver_base.GlucometerDriver): vendor = inq.result["t10_vendor_identification"][:32] if vendor != b"LifeScan": raise exceptions.ConnectionFailed( - "Device %s is not a LifeScan glucometer." % self.device_name_ + f"Device {self.device_name_} is not a LifeScan glucometer." ) def disconnect(self): # pylint: disable=no-self-use @@ -176,10 +176,11 @@ class Device(driver_base.GlucometerDriver): return response.value def get_meter_info(self): + model = self._query_string("model") return common.MeterInfo( - "OneTouch %s glucometer" % self._query_string("model"), + f"OneTouch {model} glucometer", serial_number=self.get_serial_number(), - version_info=("Software version: " + self.get_version(),), + version_info=(f"Software version: {self.get_version()}",), native_unit=self.get_glucose_unit(), ) diff --git a/glucometerutils/drivers/sdcodefree.py b/glucometerutils/drivers/sdcodefree.py index 47dd9ca..08a3afc 100644 --- a/glucometerutils/drivers/sdcodefree.py +++ b/glucometerutils/drivers/sdcodefree.py @@ -105,14 +105,14 @@ class Device(serial.SerialDevice, driver_base.GlucometerDriver): continue if challenge != b"\x53": raise exceptions.ConnectionFailed( - message="Unexpected starting bytes %r" % challenge + message=f"Unexpected starting bytes {challenge!r}" ) challenge += self.serial_.read(6) if challenge != _CHALLENGE_PACKET_FULL: raise exceptions.ConnectionFailed( - message="Unexpected challenge %r" % challenge + message=f"Unexpected challenge {challenge!r}" ) logging.debug("challenge packet received: %s", binascii.hexlify(challenge)) diff --git a/glucometerutils/drivers/td4277.py b/glucometerutils/drivers/td4277.py index 0385299..106166e 100644 --- a/glucometerutils/drivers/td4277.py +++ b/glucometerutils/drivers/td4277.py @@ -157,7 +157,7 @@ class Device(serial.SerialDevice, driver_base.GlucometerDriver): ) if response_command not in _VALID_CONNECT_RESPONSE: raise exceptions.ConnectionFailed( - "Invalid response received: %2x %r" % (response_command, message) + f"Invalid response received: {response_command:02x} {message!r}" ) _, model_message = self._send_command(_GET_MODEL) @@ -165,7 +165,7 @@ class Device(serial.SerialDevice, driver_base.GlucometerDriver): _MODEL_STRUCT.parse(model_message) except construct.ConstructError: raise exceptions.ConnectionFailed( - "Invalid model identified: %r" % model_message + f"Invalid model identified: {model_message!r}" ) def disconnect(self): diff --git a/glucometerutils/exceptions.py b/glucometerutils/exceptions.py index 52e4d22..1f72308 100644 --- a/glucometerutils/exceptions.py +++ b/glucometerutils/exceptions.py @@ -30,16 +30,13 @@ class InvalidResponse(Error): """The response received from the meter was not understood""" def __init__(self, response): - super(InvalidResponse, self).__init__( - "Invalid response received:\n%s" % response - ) + super(InvalidResponse, self).__init__(f"Invalid response received:\n{response}") class InvalidChecksum(InvalidResponse): def __init__(self, wire, calculated): super(InvalidChecksum, self).__init__( - "Response checksum not matching: %08x (wire) != %08x (calculated)" - % (wire, calculated) + f"Response checksum not matching: {wire:08x} (wire) != {calculated:08x} (calculated)" ) @@ -48,7 +45,7 @@ class InvalidGlucoseUnit(Error): def __init__(self, unit): super(InvalidGlucoseUnit, self).__init__( - "Invalid glucose unit received:\n%s" % unit + f"Invalid glucose unit received:\n{unit}" ) diff --git a/glucometerutils/glucometer.py b/glucometerutils/glucometer.py index 012bdb1..31cfdc0 100755 --- a/glucometerutils/glucometer.py +++ b/glucometerutils/glucometer.py @@ -103,7 +103,7 @@ def main(): driver = importlib.import_module("glucometerutils.drivers." + args.driver) except ImportError as e: logging.error( - 'Error importing driver "%s", please check your --driver ' "parameter:\n%s", + 'Error importing driver "%s", please check your --driver parameter:\n%s', args.driver, e, ) @@ -129,11 +129,7 @@ def main(): # Also catch any leftover ValueErrors. except (NotImplementedError, ValueError): time_str = "N/A" - print( - "{device_info}Time: {time}".format( - device_info=str(device_info), time=time_str - ) - ) + print(f"{device_info}Time: {time_str}") elif args.action == "dump": unit = args.unit if unit is None: @@ -179,7 +175,7 @@ def main(): patient_name = device.get_patient_name() if patient_name is None: patient_name = "[N/A]" - print("Patient Name: {patient_name}".format(patient_name=patient_name)) + print(f"Patient Name: {patient_name}") except NotImplementedError: print("The glucometer does not support retrieving patient name.") elif args.action == "zero": @@ -193,7 +189,7 @@ def main(): else: return 1 except exceptions.Error as err: - print("Error while executing '%s': %s" % (args.action, str(err))) + print(f"Error while executing '{args.action}': {err}") return 1 device.disconnect() diff --git a/glucometerutils/support/contourusb.py b/glucometerutils/support/contourusb.py index 3b0dc80..9afb79d 100644 --- a/glucometerutils/support/contourusb.py +++ b/glucometerutils/support/contourusb.py @@ -180,14 +180,14 @@ class ContourHidDevice(hiddevice.HidDevice): if recno != self.currecno: raise FrameError( - "Bad recno, got %r expected %r" % (recno, self.currecno), frame + f"Bad recno, got {recno!r} expected {self.currecno!r}", frame ) - checksum = self.checksum(match.group("check")) - if checksum != match.group("checksum"): + calculated_checksum = self.checksum(match.group("check")) + received_checksum = match.group("checksum") + if calculated_checksum != received_checksum: raise FrameError( - "Checksum error: got %s expected %s" - % (match.group("checksum"), checksum), + f"Checksum error: received {received_checksum} expected {calculated_checksum}", frame, ) diff --git a/glucometerutils/support/freestyle.py b/glucometerutils/support/freestyle.py index 341e978..86c53d0 100644 --- a/glucometerutils/support/freestyle.py +++ b/glucometerutils/support/freestyle.py @@ -152,8 +152,7 @@ class FreeStyleHidDevice(hiddevice.HidDevice, driver_base.GlucometerDriver, ABC) response = self._read_response() if not _is_init_reply(response): raise exceptions.ConnectionFailed( - "Connection error: unexpected message %02x:%s" - % (response[0], response[1].hex()) + f"Connection error: unexpected message %{response[0]:02x}:{response[1].hex()}" ) def disconnect(self): @@ -235,8 +234,7 @@ class FreeStyleHidDevice(hiddevice.HidDevice, driver_base.GlucometerDriver, ABC) if message_type != self.TEXT_REPLY_CMD: raise exceptions.InvalidResponse( - "Message type %02x does not match expectations: %r" - % (message_type, content) + f"Message type {message_type:02x}: content does not match expectations: {content!r}" ) full_content += content @@ -317,10 +315,8 @@ class FreeStyleHidDevice(hiddevice.HidDevice, driver_base.GlucometerDriver, ABC) # The format used by the FreeStyle devices is not composable based on # standard strftime() (namely it includes no leading zeros), so we need # to build it manually. - date_cmd = "$date,{month},{day},{year}".format( - month=date.month, day=date.day, year=(date.year - 2000) - ) - time_cmd = "$time,{hour},{minute}".format(hour=date.hour, minute=date.minute) + date_cmd = f"$date,{date.month},{date.day},{date.year - 2000}" + time_cmd = f"$time,{date.hour},{date.minute}" self._send_text_command(bytes(date_cmd, "ascii")) self._send_text_command(bytes(time_cmd, "ascii")) diff --git a/glucometerutils/support/hiddevice.py b/glucometerutils/support/hiddevice.py index ad8f3a6..43461e7 100644 --- a/glucometerutils/support/hiddevice.py +++ b/glucometerutils/support/hiddevice.py @@ -52,9 +52,7 @@ class HidDevice: # If the user passed a device path that does not exist, raise an # error. This is to avoid writing to a file instead of to a device node. if device and not os.path.exists(device): - raise exceptions.ConnectionFailed( - message="Path %s does not exist." % device - ) + raise exceptions.ConnectionFailed(message=f"Path {device} does not exist.") # If the user passed a device, try opening it. if device: @@ -73,7 +71,7 @@ class HidDevice: ) except OSError as e: raise exceptions.ConnectionFailed( - message="Unable to connect to meter: %s." % e + message=f"Unable to connect to meter: {e}." ) def _write(self, report): diff --git a/glucometerutils/support/lifescan.py b/glucometerutils/support/lifescan.py index 9340e49..1c329c6 100644 --- a/glucometerutils/support/lifescan.py +++ b/glucometerutils/support/lifescan.py @@ -11,7 +11,7 @@ class MissingChecksum(exceptions.InvalidResponse): def __init__(self, response): super(MissingChecksum, self).__init__( - "Response is missing checksum: %s" % response + f"Response is missing checksum: {response}" ) @@ -20,13 +20,13 @@ class InvalidSerialNumber(exceptions.Error): def __init__(self, serial_number): super(InvalidSerialNumber, self).__init__( - "Serial number %s is invalid." % serial_number + f"Serial number {serial_number} is invalid." ) class MalformedCommand(exceptions.InvalidResponse): def __init__(self, message): - super(MalformedCommand, self).__init__("Malformed command: %s" % message) + super(MalformedCommand, self).__init__(f"Malformed command: {message}") def crc_ccitt(data): diff --git a/reversing_tools/abbott/freestyle_hid_console.py b/reversing_tools/abbott/freestyle_hid_console.py index 5005e4a..654a97c 100755 --- a/reversing_tools/abbott/freestyle_hid_console.py +++ b/reversing_tools/abbott/freestyle_hid_console.py @@ -56,12 +56,12 @@ def main(): command = input(">>> ") else: command = input() - print(">>> {command}".format(command=command)) + print(f">>> {command}") try: print(device._send_text_command(bytes(command, "ascii"))) except exceptions.InvalidResponse as error: - print("! {error}".format(error=error)) + print(f"! {error}") if __name__ == "__main__": -- cgit v1.2.3